import Vue from 'vue'

import 'normalize.css/normalize.css' // A modern alternative to CSS resets

import ElementUI from 'element-ui'
// import 'element-ui/lib/theme-chalk/index.css'
import 'element-ui/packages/theme-chalk/src/index.scss'
// import locale from 'element-ui/lib/locale/lang/en' // lang i18n

import '@/styles/index.scss' // global css

import App from './App'
import store from './store'
import router from './router'

// 代码编辑器
import VueCodemirror from 'vue-codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/mode/javascript/javascript.js'
import 'codemirror/mode/css/css.js'
import 'codemirror/mode/htmlmixed/htmlmixed.js'


import locale from 'element-ui/lib/locale/lang/zh-CN'

import '@/icons' // icon
import '@/permission' // permission control
import './assets/tabler-icons.css'

Vue.prototype.hashmap = hashmap
Vue.prototype.hashmap = hashmap
Vue.prototype.findJsonByKeyValue = function(source, key, val) {
  if (val === null) {
    return false
  }
  if (val === undefined) {
    return false
  }
  if (val === '') {
    return false
  }
  for (let i = 0; i < source.length; i++) {
    const json = source[i]
    if ((json[key] !== undefined) && (json[key] !== null)) {
      if (json[key].toString() === val.toString()) {
        return json
      }
    }
  }
  return false
}
/**
 * 将字符串或数字转为更简洁的数字表示：
 * - 如果是整数（如 "5"、"5.0000"），返回整数 5
 * - 如果是小数（如 "123.4500"），去掉多余的尾部 0，返回 123.45
 * - 如果不是合法数字（如 "abc"），则原样返回
 *
 * @param {string|number} val - 原始值
 * @returns {number|string} - 转换后的数字或原始字符串
 */
Vue.prototype.normalizeNumber = function(val) {
  const num = Number(val)
  if (Number.isNaN(num)) return val // 非数字，原样返回

  if (Number.isInteger(num)) return num

  if (typeof val === 'string' || typeof val === 'number') {
    const floatStr = String(val).trim()

    // 如果是整数形式的小数（如 5.0000）
    if (/^-?\d+(\.0+)?$/.test(floatStr)) {
      return Math.trunc(num)
    }

    // 如果是合法的小数，就去掉末尾0（toString 会保留准确精度）
    const stripped = parseFloat(floatStr) // 自动去掉末尾0
    return stripped
  }

  return num
}
/**
 * 遍历对象所有字段，对 string 或 number 类型的值：
 * - 如果是整数或带尾部 0 的小数（如 "8.000"），转为整数 8
 * - 如果是小数（如 "123.4500"），去掉末尾 0，转为 123.45
 * - 非数字字符串、数组、对象等保持原样不变
 * 用于格式化整行数据中的数值字段，统一展示或计算使用。
 *
 * @param {object} row - 一行数据对象
 * @returns {object} - 新对象，所有数值字段更简洁
 */
Vue.prototype.normalizeRowNumbers = function(row, skipKeys = []) {
  if (!row || typeof row !== 'object' || Array.isArray(row)) return row

  const newRow = {}
  for (const key in row) {
    if (!Object.prototype.hasOwnProperty.call(row, key)) continue

    const val = row[key]

    // 如果在 skipKeys 中，跳过转换
    if (skipKeys.includes(key)) {
      newRow[key] = val
      continue
    }

    if (typeof val === 'string' || typeof val === 'number') {
      try {
        newRow[key] = this.normalizeNumber(val)
      } catch (e) {
        newRow[key] = val
      }
    } else {
      newRow[key] = val
    }
  }

  return newRow
}


Vue.prototype.formatAbbrNum = function(num) {
  if (typeof num !== 'number' || isNaN(num)) return ''

  if (num >= 1_000_000_000) {
    return (num / 1_000_000_000).toPrecision(6).replace(/\.?0+$/, '') + 'B'
  } else if (num >= 1_000_000) {
    return (num / 1_000_000).toPrecision(6).replace(/\.?0+$/, '') + 'M'
  } else if (num >= 1_000) {
    return (num / 1_000).toPrecision(6).replace(/\.?0+$/, '') + 'K'
  } else {
    return num.toString()
  }
}
Vue.prototype.formatSmartTime = function(input) {
  // 1. 自动处理字符串或数字类型
  let timestamp = typeof input === 'string' ? parseFloat(input) : input
  if (isNaN(timestamp)) return '无效时间'

  // 2. 判断单位：如果是秒，乘1000 转为毫秒
  if (timestamp < 1e12) {
    timestamp *= 1000
  }

  // 3. 转为北京时间对象（Date内部是UTC时间，构造时自动处理）
  const inputTime = new Date(timestamp)
  const now = new Date()

  // 4. 差值计算（基于北京时间）
  const diffMs = now - inputTime
  const diffSec = Math.floor(diffMs / 1000)
  const diffMin = Math.floor(diffSec / 60)
  const diffHour = Math.floor(diffMin / 60)

  const pad = n => n.toString().padStart(2, '0')
  const timePart = `${pad(inputTime.getHours())}:${pad(inputTime.getMinutes())}:${pad(inputTime.getSeconds())}`

  if (diffSec < 10) return '刚刚'
  if (diffMin < 1) return `${diffSec}秒前`
  if (diffMin < 30) return `${diffMin}分钟前`
  if (diffHour < 1) return '30分钟前'
  if (diffHour < 2) return '1小时内'
  if (diffHour < 3) return '2小时内'

  const inputDate = inputTime.toDateString()
  const nowDate = now.toDateString()

  if (inputDate === nowDate) {
    return `今天 ${timePart}`
  }

  const yesterday = new Date()
  yesterday.setHours(0, 0, 0, 0)
  yesterday.setDate(yesterday.getDate() - 1)

  if (inputDate === yesterday.toDateString()) {
    return `昨天 ${timePart}`
  }

  return `${inputTime.getMonth() + 1}月${inputTime.getDate()}日 ${timePart}`
}

// 判断登录人员身份
Vue.prototype.getRoleType = function() {
  const userinfo_store = localStorage.getItem('userInfo')
  const userinfo = JSON.parse(userinfo_store)

  if (userinfo && userinfo.role) { 
    return userinfo.role
  } else {
    return 0
  }
}

Vue.prototype.openXq = function(code, target = '_blank') {
  code = code.includes('.') ? code.split('.')[1] : code
  const url = `https://xueqiu.com/S/${code}`
  window.open(url, target)
}

Vue.prototype.$isMobile = window.innerWidth < 768

window.addEventListener('resize', () => {
  Vue.prototype.$isMobile = window.innerWidth < 768
})

/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online ! ! !
 */
if (process.env.NODE_ENV === 'production') {
  const { mockXHR } = require('../mock')
  mockXHR()
}
import './styles/element-variables.scss'
import hashmap from './hash.js'
// set ElementUI lang to EN
Vue.use(ElementUI, { locale })
Vue.use(VueCodemirror)
// 如果想要中文版 element-ui，按如下方式声明
// Vue.use(ElementUI)

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
